<?php
use Core\Mvc\Controller;
use Phalcon\Di;

function nodeActionLink($node)
{
    $di = Di::getDefault();
    $output = [
        'up' => [
            'label' => '上一篇',
            'href' => '#null',
            'title' => '没有了～'
        ],
        'next' => [
            'label' => '下一篇',
            'href' => '#null',
            'title' => '没有了～'
        ]
    ];
    $upNode = $di->getShared('entityManager')->get('node', [
        'conditions' => [
            'created' => [
                '$lt' => $node->created
            ]
        ]
    ]);
    $nextNode = $di->getShared('entityManager')->get('node', [
        'conditions' => [
            'created' => [
                '$gt' => $node->created
            ]
        ]
    ]);

    if ($upNode) {
        $output['up']['href'] = $di->getShared('url')->get(['for' => 'node', 'contentModel' => $upNode->contentModel, 'id' => $upNode->getId()]);
        $output['up']['title'] = $upNode->title;

    }

    if ($nextNode) {
        $output['next']['href'] = $di->getShared('url')->get(['for' => 'node', 'contentModel' => $nextNode->contentModel, 'id' => $nextNode->getId()]);
        $output['next']['title'] = $nextNode->title;
    }

    return $output;
}

function nodeRender(\Modules\Node\Entity\Node $node, $template = null)
{
    if (!is_null($template)) {
        $template = [
            'node',
            'node-' . $template,
            'node-' . $node->contentModel,
            'node-' . $node->contentModel . '-' . $template,
            'node-' . $node->getId(),
        ];
    } else {
        $template = [
            'node',
            'node-' . $node->contentModel,
            'node-' . $node->getId(),
        ];
    }
    return array(
        '#templates' => $template,
        'data' => $node
    );
}

function nodeList($query)
{
    $di = \Phalcon\Di::getDefault();
    $node = $di->getShared('entityManager')->find('node', $query);
    return $node;
}

function isNode()
{
    $di = Di::getDefault();
    $controllerName = strtolower($di->getShared('dispatcher')->getControllerName());
    $actionName = strtolower($di->getShared('dispatcher')->getActionName());
    $module = strtolower($di->getShared('router')->getModuleName());

    if ($module == 'node' && $controllerName == 'index' && $actionName == 'index') {
        return true;
    }
    return false;
}

function getNode()
{
    if (isNode()) {
        return Controller::$variables['data'];
    }
    return false;
}

function zanNode($node)
{
    return [
        '#templates' => [
            'nodeZan',
            'nodeZan-' . $node->contentModel
        ],
        'data' => $node
    ];
}